/*
 * @Author: your name
 * @Date: 2019-11-01 10:17:50
 * @LastEditTime: 2019-11-01 17:14:59
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \koa-example\src\controllers\public.js
 */

const cheerio = require('cheerio');
const superagent = require('superagent');
const charset = require('superagent-charset');
charset(superagent);


const loginUrl = 'https://account.geekbang.org/account/ticket/login'

const params =  {
  appid: 1,
  captcha: "",
  cellphone: "15680686538",
  country: 86,
  password: "a15680686538.",
  platform: 3,
  remember: 1,
  source: ""
}

function getCookie() {
  superagent.post(loginUrl)
      .type('form')
      .send(params)
      .end(function(err, res) {
          if (err) {
              handleErr(err.message);
              return;
          }
          cookie = res.header['set-cookie']; //从response中得到cookie
          emitter.emit("setCookeie");
      })
}

const spiderUurl = 'https://time.geekbang.org/column/article/113550';

function getDetailData(){
  // 请求用户信息接口，来判断登录是否还有效，在产品详情页判断麻烦还要造成五次登录请求
  superagent
      .post(spiderUurl)
      .set('Cookie', cookie)
      .end(function(err,pres){
      // 常规的错误处理
      if (err) {
          handleErr(err.message);
          return;
      }
      let retcode = JSON.parse(pres.text).retcode;
      if(retcode === 410){
          handleErr('登陆cookie已失效，尝试重新登陆...');
          getCookie();
          return;
      }
      var reptileLink = function(url,callback){
          // 如果爬取页面有限制爬取次数，这里可设置延迟
          console.log( '正在爬取产品详情页面：' + url);
          superagent
              .get(url)
              .set('Cookie', cookie)
              .end(function(err,pres){
                  // 常规的错误处理
                  if (err) {
                      handleErr(err.message);
                      return;
                  }
                  var $ = cheerio.load(pres.text);
                  var records = [];
                  var $table = $('._2c4hPkl9').innerHTML();
                  
                  fs.writeFileSync('data/prod.json', JSON.stringify($table));
              });
      };
  });
}

module.exports = {
  getDetailData,
  getCookie
}